<template>
  <div>
    <!--    &lt;!&ndash; 添加重庆聚焦按钮 &ndash;&gt;-->
    <!--    <a-button-->
    <!--      style="position: absolute; top: 10px; left: 20px; z-index: 1000"-->
    <!--      type="primary"-->
    <!--      @click="focusChongqing"-->
    <!--    >-->
    <!--      显示重庆行政区划-->
    <!--    </a-button>-->

    <el-dialog
      width="80%"
      :visible="formVisible1"
      title="资产详情"
      @close="formVisible1=false"
    >

      <JNPF-Form @close="colseFlow" ref="JNPFForm"/>

    </el-dialog>
    <!-- 添加区域统计卡片 -->
    <div v-show="false" class="region-stats"
         style="position: absolute; top: 60px; left: 20px; z-index: 1000; background-color: white; padding: 10px; border-radius: 5px; box-shadow: 0 2px 10px rgba(0,0,0,0.1);"
    >
      <h3>区域统计</h3>
      <div
        v-for="(count, region) in regionStats"
        :key="region"
        class="region-item"
        @click="focusRegion(region)"
        :style="{ cursor: 'pointer', backgroundColor: activeRegion === region ? '#e6f7ff' : 'transparent' }"
      >
        <span>{{ region }}: </span>
        <span class="count">{{ count }}个资产</span>
      </div>
    </div>

    <div class="asset-table">
      <table>
        <thead>
        <tr>
          <th class="region-header">地区</th>
          <th class="region-header">资产数量</th>
          <!--          <th>建筑面积(m²)</th>-->
          <!--          <th>土地面积(m²)</th>-->
        </tr>
        </thead>
        <tbody>
        <!-- 全国数据 -->
        <!--        <tr class="nation-row">-->
        <!--          <td>全国</td>-->
        <!--          <td class="number">{{ formatNumber(nationData.buildArea) }}</td>-->
        <!--          <td class="number">{{ formatNumber(nationData.landArea) }}</td>-->
        <!--        </tr>-->
        <!-- 城市数据 -->
        <tr v-for="(city, index) in cityData" :key="index">
          <td @click="focusRegion(city.name)">
            <div class="city-cell">
              <a href="#">{{ city.name }}</a>
            </div>
          </td>
          <td class="number"><span class="asset-count">{{ city.assets }}个资产 ></span>
          </td>

          <!--          <td class="number">{{ formatNumber(city.buildArea) }}</td>-->
          <!--          <td class="number">{{ formatNumber(city.landArea) }}</td>-->
        </tr>
        </tbody>
      </table>
    </div>
    <div id="test-map" style="height: 100vh;width: 99%" v-show="shabi"/>
  </div>
</template>

<script>
import { lazyAMapApiLoaderInstance } from 'vue-amap'
import request from '@/utils/request'
import JNPFForm from './FormDetai1'

export default {
  mixins: [],
  components: { JNPFForm },
  data() {
    return {
      shabi: true,
      nationData: {
        buildArea: 110300,
        landArea: 0
      },
      cityData: [
        // {
        //   name: '北京市',
        //   buildArea: 0,  // 自行修改数据
        //   landArea: 0,   // 自行修改数据
        //   assets: 0
        // },
        {
          name: '重庆市',
          buildArea: 0,  // 自行修改数据
          landArea: 0,   // 自行修改数据
          assets: 0
        },
        // {
        //   name: '四川省',
        //   buildArea: 0,
        //   landArea: 0,
        //   assets: 0
        // }
      ],
      districtCounts: '',
      url: {},
      columns: [
        {
          title: '资产名称',
          align: 'center',
          dataIndex: 'assetName',
          width: 250
        },
        {
          title: '操作',
          dataIndex: 'action',
          align: 'center',
          width: 50,
          scopedSlots: { customRender: 'action' }
        }
      ],
      formVisible1: false,
      map: null, // 地图
      pointSimplifier: null,
      district: null,
      markerList: [],
      mapData: [], // 存储地图点数据
      regionStats: {}, // 区域统计结果
      pointRegionMap: {}, // 点与区域的映射关系
      activeRegion: null, // 当前激活的区域
      regionPolygons: [] // 区域多边形覆盖物
    }
  },
  async created() {
    // 加载高德地图API
    this.initMap()
    var that = this
    // 发送请求
    const res = await request({
      url: `/api/example/ZcglZcdjInfo/getList`,
      method: 'post',
      data: { longitude: "101.57088", latitude: "29.553074" }
    })

    // // 检查响应数据格式
    // if (!res.data || !res.data.list || res.data.list.length === 0) {
    //   console.error('响应数据格式不符合预期:', res)
    //   that.$message.error('获取详情数据失败')
    //   return
    // }
    // that.formVisible1 = true
    that.$nextTick(() => {
      that.$refs.JNPFForm.init(res.data.list[0])
    })
    that.$forceUpdate()
  },
  methods: {
    colseFlow() {

      this.formVisible1 = false

    },
    async focusChongqing() {
      this.activeRegion = '重庆市'
      await this.focusOnRegion('重庆市')
    },

    // 聚焦到指定区域
    async focusRegion(region) {
      this.activeRegion = region
      await this.focusOnRegion(region)
    },

    // 处理区域聚焦逻辑
    async focusOnRegion(region) {
      try {
        // 确保地图已初始化
        if (!this.map) {
          throw new Error('地图尚未初始化')
        }

        // 清除之前的区域多边形
        if (this.regionPolygons.length > 0) {
          this.map.remove(this.regionPolygons)
          this.regionPolygons = []
        }

        // 确保AMap加载完成
        await lazyAMapApiLoaderInstance.load()

        // 检查插件是否已加载
        if (!window.AMap.DistrictSearch) {
          await new Promise(resolve => {
            AMap.plugin('AMap.DistrictSearch', resolve)
          })
        }

        // 创建行政区划查询实例
        const districtSearch = new AMap.DistrictSearch({
          level: 'district',
          subdistrict: 0,
          extensions: 'all'
        })

        // 提取区域名称中的省市信息
        let province = ''
        let city = ''
        let district = ''

        // 处理特殊情况：直辖市
        if (region.startsWith('重庆市') || region.startsWith('北京市') || region.startsWith('上海市') || region.startsWith('天津市')) {
          province = region.substring(0, 3)
          if (region.length > 3) {
            district = region.substring(3)
          }
        } else {
          // 普通省份
          const provinceMatch = region.match(/^[\u4e00-\u9fa5]+省|^[\u4e00-\u9fa5]+自治区/)
          if (provinceMatch) {
            province = provinceMatch[0]
            city = region.replace(province, '')
          } else {
            // 处理没有明确省份的情况
            city = region
          }
        }

        // 构建查询关键词
        let keyword = ''
        if (province && district) {
          keyword = `${province}${district}`
        } else if (province && city) {
          keyword = city
        } else if (province) {
          keyword = province
        } else if (city) {
          keyword = city
        }

        if (!keyword) {
          console.error('无法解析区域关键词:', region)
          return
        }

        // 查询区域信息
        districtSearch.search(keyword, (status, result) => {
          try {
            if (status === 'complete' && result.districtList && result.districtList.length > 0) {
              const bounds = result.districtList[0].boundaries
              if (!bounds || bounds.length === 0) {
                console.error('未找到区域边界:', keyword)
                return
              }

              // 绘制行政区划边界
              const polygons = []
              bounds.forEach(boundary => {
                const polygon = new AMap.Polygon({
                  path: boundary,
                  strokeColor: '#FF33FF',
                  strokeWeight: 2,
                  fillColor: '#1791fc',
                  fillOpacity: 0.2
                })
                polygons.push(polygon)
                if (this.map) {
                  this.map.add(polygon)
                }
              })

              // 保存多边形实例
              this.regionPolygons = polygons

              // 调整视野到区域范围
              if (this.map) {
                this.map.setFitView(polygons)
                // 根据区域大小调整缩放级别
                const zoom = this.getZoomLevelByRegion(keyword)
                if (zoom) {
                  this.map.setZoom(zoom)
                }
              }
            } else {
              console.error('行政区划查询失败:', result)
            }
          } catch (error) {
            console.error('处理查询结果时出错:', error)
          }
        })
      } catch (error) {
        console.error('加载插件或地图未初始化出错:', error)
      }
    },

    // 根据区域名称获取适当的缩放级别
    getZoomLevelByRegion(region) {
      // 这里可以根据实际需求调整各区域的缩放级别
      if (region.includes('重庆') || region.includes('北京') || region.includes('上海') || region.includes('天津')) {
        return 10 // 直辖市级别
      } else if (region.includes('省') || region.includes('自治区')) {
        return 6 // 省份级别
      } else if (region.includes('市') || region.includes('地区')) {
        return 8 // 城市级别
      } else if (region.includes('区') || region.includes('县')) {
        return 11 // 区县级别
      }
      return null
    },

    formatNumber(num) {
      return num.toLocaleString('en-US', { minimumFractionDigits: 2 })
    },
    clear() {
      if (this.map) {
        this.map.remove(this.markerList)
      }
    },
    /**
     * 点击表格行触发
     * @param {Object} record - 行数据
     * @param {Number} index - 索引值
     * @return Function
     */
    rowClick: function(record, index) {
      return {
        on: {
          click: () => {
            this.getCoordinate(record.longitude, record.latitude)
          },
          dblclick: () => {
            console.log('双击了我')
          }
        }
      }
    },
    entercq() {

    },
    // 初始化地图相关实例
    initMap() {
      const that = this
      lazyAMapApiLoaderInstance.load().then(() => {
        that.map = new AMap.Map('test-map', {
          zooms: [3, 18], // 地图缩放范围
          center: new AMap.LngLat(116.397428, 39.90923)
        })
        // 加载海量点组件
        AMapUI.loadUI(['misc/PointSimplifier'], (PointSimplifier) => {
          if (!PointSimplifier.supportCanvas) {
            alert('当前环境不支持 Canvas！')
            return
          }
          // 创建组件实例
          that.pointSimplifier = new PointSimplifier({
            map: that.map,
            // data是海量点的坐标，下面是随机产生点坐标的方法
            // 返回要显示的点坐标
            autoSetFitView: false, //禁止自动更新地图视野
            zIndex: 110,
            getPosition: function(item) {
              // item  为 setMapData()方法里mapData里的每一项
              if (!item) {
                return null
              }
              var parts = item.split(',')
              //返回经纬度 [lng, lat]
              return [parseFloat(parts[0]), parseFloat(parts[1])]
            },
            pointClick: function(dataItem, idx) {
              return idx + ': ' + dataItem
            },
            // getHoverTitle: function (dataItem, idx) {
            //   return JSON.parse(dataItem.substring(dataItem.indexOf("{"), dataItem.length));
            //   // return "别墅区";
            // },
            renderOptions: {
              //点的样式
              pointStyle: {
                width: 16,
                height: 16,
                fillStyle: 'blue'
              },
              //鼠标hover时的title信息
              hoverTitleStyle: {
                position: 'top'
              }
            }
          })
          // 为海量点添加点击事件
          that.pointSimplifier.on('pointClick', async function(e, record) {
            try {
              console.log('点击了地图点，坐标:', record.data)

              // 解析经纬度
              const [longitude, latitude] = record.data.split(',')

              // 发送请求
              const res = await request({
                url: `/api/example/ZcglZcdjInfo/getList`,
                method: 'post',
                data: { longitude, latitude }
              })

              console.log('详情请求响应:', res)

              // 检查响应数据格式
              if (!res.data || !res.data.list || res.data.list.length === 0) {
                console.error('响应数据格式不符合预期:', res)
                that.$message.error('获取详情数据失败')
                return
              }

              that.formVisible1 = true
              that.$nextTick(() => {
                that.$refs.JNPFForm.init(res.data.list[0])
              })
              that.$forceUpdate()

            } catch (error) {
              console.error('获取详情时出错:', error)
              that.$message.error('获取详情失败: ' + error.message)
            }
          })
          //加载相关组件
          AMapUI.load(['ui/geo/DistrictCluster', 'lib/utils'], function(
            DistrictCluster,
            utils
          ) {
            // 定义行政区划聚合实例
            that.district = new DistrictCluster({
              // excludedAdcodes: [130000, 610000, 340000],
              map: that.map, //所属的地图实例
              //返回数据项中的经纬度位置
              getPosition: function(item) {
                if (!item) {
                  return null
                }
                var parts = item.split(',')
                //返回经纬度 [lng, lat]
                return [parseFloat(parts[0]), parseFloat(parts[1])]
              }
            })
            that.setMapData()
          })
        })
      })
    },
    getCoordinate(c, b) {
      var a = []
      a[0] = c
      a[1] = b
      if (this.map) {
        this.marker = new AMap.Marker({
          title: 'mark',
          zoomToAccuracy: true,
          position: a //位置
        })
        this.map.add(this.marker) //添加到地图
        this.markerList.push(this.marker)
        // 传入经纬度，设置地图中心点
        this.map.setCenter(a)
      }
    },
    setMapData() {
      // 地图点的数据
      request({
        url: `/api/example/ZcglZcdjInfo/listAddress`,
        method: 'get'
      }).then(res => {
        // 存储原始数据
        const originalData = res.data
        // 处理数据并统计区域
        this.processMapData(originalData)
      })
    },
    // 处理地图数据并统计区域
    async processMapData(data) {
      const that = this
      // 重置统计结果
      this.regionStats = {}
      this.pointRegionMap = {}

      // 确保AMap加载完成
      await lazyAMapApiLoaderInstance.load()

      // 检查插件是否已加载
      if (!window.AMap.Geocoder) {
        await new Promise(resolve => {
          AMap.plugin('AMap.Geocoder', resolve)
        })
      }

      // 创建地理编码实例
      const geocoder = new AMap.Geocoder({
        radius: 1000,
        extensions: 'all'
      })

      // 遍历每个点查询所属区域
      for (let i = 0; i < data.length; i++) {
        const point = data[i]
        const lng = parseFloat(point.longitude)
        const lat = parseFloat(point.latitude)

        // 使用逆地理编码查询点所在区域
        await new Promise(resolve => {
          geocoder.getAddress([lng, lat], (status, result) => {
            if (status === 'complete' && result.regeocode) {
              // 获取省、市、区信息
              const province = result.regeocode.addressComponent.province
              const city = result.regeocode.addressComponent.city || province
              const district = result.regeocode.addressComponent.district

              // 构建区域名称
              let regionName = ''
              if (province === '重庆市' || province === '北京市' || province === '上海市' || province === '天津市') {
                // 直辖市特殊处理
                regionName = district ? `${province}${district}` : province
              } else {
                regionName = city ? `${province}${city}` : province
              }

              // 更新统计信息
              that.regionStats[regionName] = (that.regionStats[regionName] || 0) + 1
              // 记录点与区域的映射关系
              that.pointRegionMap[`${lng},${lat}`] = regionName

              // 更新城市数据中的资产数量
              const cityIndex = that.cityData.findIndex(item => item.name === province || item.name === city)
              if (cityIndex !== -1) {
                that.cityData[cityIndex].assets += 1
              }
            } else {
              console.error('获取地址失败:', result)
              // 默认归类到未知区域
              that.regionStats['未知区域'] = (that.regionStats['未知区域'] || 0) + 1
              that.pointRegionMap[`${lng},${lat}`] = '未知区域'
            }
            resolve()
          })
        })
      }

      // 构建地图数据
      const mapData = data.map(item => `${item.longitude},${item.latitude}`)
      this.mapData = mapData

      // 更新地图显示
      if (this.pointSimplifier) {
        this.pointSimplifier.setData(mapData)
      }
      if (this.district) {
        this.district.setData(mapData)
      }

      // 更新全国数据中的资产总数
      this.nationData.assets = data.length

      console.log('区域统计结果:', this.regionStats)
      console.log('点区域映射:', this.pointRegionMap)
    },
    formatDate: function(value) {
      let date = new Date(value)
      let y = date.getFullYear()
      let MM = date.getMonth() + 1
      MM = MM < 10 ? ('0' + MM) : MM
      let d = date.getDate()
      d = d < 10 ? ('0' + d) : d
      let h = date.getHours()
      h = h < 10 ? ('0' + h) : h
      let m = date.getMinutes()
      m = m < 10 ? ('0' + m) : m
      let s = date.getSeconds()
      s = s < 10 ? ('0' + s) : s
      if (value == null || value == '') {
        return ''
      }
      return y + '-' + MM + '-' + d + ' ' + h + ':' + m
    }
  },
  mounted() {
    // 这里不需要再次调用initMap，因为已经在created钩子中调用了
  }
}
</script>

<style scoped>
.region-stats {
  max-width: 200px;
  font-size: 14px;
}

.region-item {
  display: flex;
  justify-content: space-between;
  margin-bottom: 5px;
  padding: 5px;
  border-radius: 3px;
  transition: background-color 0.2s;
}

.region-item:hover {
  background-color: #f5f7fa;
}

.count {
  font-weight: bold;
  color: #1890ff;
}

.asset-table {
  position: absolute;
  top: 10px;
  left: 20px;
  z-index: 1000;
  background-color: white;
  border-radius: 5px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  max-width: 300px;
  overflow: hidden;
}

table {
  width: 100%;
  border-collapse: collapse;
}

th, td {
  padding: 8px 12px;
  text-align: left;
  border-bottom: 1px solid #eee;
}

th {
  background-color: #f5f7fa;
  font-weight: 600;
}

.nation-row {
  font-weight: bold;
}

.city-cell {
  min-width: 100px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.asset-count {
  font-size: 12px;
  color: #8c8c8c;
}

.number {
  text-align: right;
}

/*/deep/.amap-ui-district-cluster-marker level_city adcode_511000 descendant_of_100000 descendant_of_510000 child_of_510000{*/
/*  height: 36px!important;*/
/*}*/
/*/deep/.amap-ui-district-cluster-marker-title{*/
/*  height: 36px!important;*/
/*  line-height: 36px!important;*/

/*}*/
/deep/ .amap-ui-district-cluster-marker span {
  /*padding: 10px!important;*/
  height: 19px !important;
  line-height: 16px !important;
}
</style>
